package com.zheng1.envii.ui.screens

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.pulltorefresh.PullToRefreshContainer
import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.layout.onPlaced
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.rememberMultiplePermissionsState
import com.zheng1.envii.MainViewModel
import com.zheng1.envii.Screen
import com.zheng1.envii.btutils.BleDeviceStatus
import com.zheng1.envii.ui.components.DeviceCard
import com.zheng1.envii.ui.components.DeviceStatus
import com.zheng1.envii.ui.theme.EnvIITheme
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.map


@OptIn(ExperimentalMaterial3Api::class, ExperimentalPermissionsApi::class)
@Composable
fun DeviceManagerScreen( modifier: Modifier = Modifier,
                         navController: NavController,
                         viewModel: MainViewModel,
) {

    val permissionState = rememberMultiplePermissionsState( permissions = listOf(
        android.Manifest.permission.BLUETOOTH_SCAN,
        android.Manifest.permission.BLUETOOTH_CONNECT,
        android.Manifest.permission.ACCESS_FINE_LOCATION,
        android.Manifest.permission.ACCESS_COARSE_LOCATION
    ) )

    var hasPermission by remember {
        mutableStateOf( false)
    }


    val connectedDeviceListState by viewModel.connectedDeviceList.collectAsState()
    val readyForConnectDeviceListState by viewModel.readyForConnectDeviceList.collectAsState()
    val scanStatus by viewModel.scanStatus.collectAsState()

    Scaffold(
        topBar = {
            CenterAlignedTopAppBar(
                colors = TopAppBarDefaults.mediumTopAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primary,
                ),
                title = {
                    Text(text = "EnvII")
                },
                actions = {
                    if(!scanStatus){
                        IconButton(
                            onClick = {
                                viewModel.startScan()
                            }
                        ) {
                            Icon(imageVector = Icons.Default.Refresh,
                                contentDescription = "refresh")
                        }
                    }else{
                        IconButton(
                            onClick = {
                                viewModel.stopScan()
                            }
                        ) {
                            Icon(imageVector = Icons.Default.Close,
                                contentDescription = "Stop")
                        }
                    }

                }
            )
        }
    ) { paddingValues ->
        Box(modifier = Modifier
            .padding(paddingValues)
            .fillMaxWidth()
            .onPlaced {
                if (!permissionState.allPermissionsGranted) {
                    permissionState.launchMultiplePermissionRequest()
                }
                if (permissionState.allPermissionsGranted) {
                    hasPermission = true
                }
            }
        ){
            if( hasPermission ){
                if( scanStatus ){
                    LinearProgressIndicator(modifier.fillMaxWidth(), color = MaterialTheme.colorScheme.secondary)
                }

                LazyColumn  {
                    if( connectedDeviceListState.isNotEmpty() ){
                        item {
                            Box(modifier = Modifier
                                .padding(top = 20.dp, bottom = 5.dp, start = 10.dp, end = 10.dp)
                                .clip(MaterialTheme.shapes.extraLarge)
                                .background(MaterialTheme.colorScheme.primary),
                                contentAlignment = Alignment.Center
                            ){
                                Text(modifier = Modifier.padding(horizontal = 10.dp),
                                    text = "已连接设备"
                                )
                            }
                        }
                    }

                    items(connectedDeviceListState){ item->
                        val deviceStatus = item.connectStatus.map {
                            when(it){
                                BleDeviceStatus.CONNECTED -> DeviceStatus.CONNECTED
                                BleDeviceStatus.CONNECTING -> DeviceStatus.CONNECTING
                                BleDeviceStatus.DISCONNECTED -> DeviceStatus.DISCONNECTED
                            }
                        }.collectAsState(initial = DeviceStatus.DISCONNECTED)

                        DeviceCard(
                            modifier = Modifier.animateItem(),
                            deviceName = item.name,
                            deviceAddress = item.address,
                            deviceRssi = item.rssi.toString(),
                            deviceConnectSatus = deviceStatus.value,
                            onButtonClick = { item.disConnect() },
                            onClick = {
                                navController.navigate(Screen.DeviceControlScreen.route.replace("{address}", item.address))
                            }
                        )
                    }

                    if( readyForConnectDeviceListState.isNotEmpty() ){
                        item {
                            Box(modifier = Modifier
                                .padding(top = 20.dp, bottom = 5.dp, start = 10.dp, end = 10.dp)
                                .clip(MaterialTheme.shapes.extraLarge)
                                .background(MaterialTheme.colorScheme.primary),
                                contentAlignment = Alignment.Center
                            ){
                                Text(modifier = Modifier.padding(horizontal = 10.dp),
                                    text = "可用设备"
                                )
                            }
                        }
                    }

                    items(readyForConnectDeviceListState){ item->
                        val deviceStatus = item.connectStatus.map {
                            when(it){
                                BleDeviceStatus.CONNECTED -> DeviceStatus.CONNECTED
                                BleDeviceStatus.CONNECTING -> DeviceStatus.CONNECTING
                                BleDeviceStatus.DISCONNECTED -> DeviceStatus.DISCONNECTED
                            }
                        }.collectAsState(initial = DeviceStatus.DISCONNECTED)
                        DeviceCard(
                            modifier = Modifier.animateItem(),
                            deviceName = item.name,
                            deviceAddress = item.address,
                            deviceRssi = item.rssi.toString(),
                            deviceConnectSatus = deviceStatus.value,
                            onButtonClick = {
                                viewModel.connect(item)
                            },
                            onClick = {

                            }
                        )
                    }
                }
            }else{
                Text(text = "没有权限", modifier = Modifier.padding(20.dp))
            }
        }
    }



}


//@Preview(showBackground = true)
//@Composable
//fun DeviceManagerScreenPreview() {
//    val navController = rememberNavController()
//    EnvIITheme( dynamicColor = false, darkTheme = false ) {
//        DeviceManagerScreen(
//            navController = navController,
//            connectedDeviceList = deviceCardList,
//            readyForConnectDeviceList = deviceCardList
//        )
//    }
//
//}